<template>
    <div class="container-fluid">
        <div class="row page-title">
            <div class="col-xs-11">
                <h1>人员管理</h1>
            </div>
            <div class="col-xs-1">
                <a title="添加" @click="add('')">
                    <el-tooltip content="添加" placement="top">
                        <i class="el-icon-plus"></i>
                    </el-tooltip>
                </a>
            </div>
        </div>
        <el-row>
            <el-form :inline="true" :model="searchForm">
                <el-form-item label="场馆名称">
                    <el-input clearable v-model="searchForm.gymName"></el-input>
                </el-form-item>
                <el-form-item label="用户名">
                    <el-input clearable v-model="searchForm.userName"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="search">查询</el-button>
                </el-form-item>
            </el-form>
        </el-row>
        <el-row>
            <el-col :span="24" class="table-bottom-margin">
                <el-table v-loading="loading" :data="tableData" border style="width: 100%" :header-cell-class-name="headerbg">
                    <!-- <el-table-column prop="userId" label="人员编号"> </el-table-column> -->
                    <el-table-column prop="userName" label="用户名"></el-table-column>
                    <el-table-column prop="gymName" label="场馆"></el-table-column>
                    <el-table-column label="用户等级">
                        <span slot-scope="scope">{{scope.row.userLevel?'场馆管理员':'总控台'}}</span>
                    </el-table-column>
                    <el-table-column label="是否有效">
                        <span slot-scope="scope">{{scope.row.valid?'是':'否'}}</span>
                    </el-table-column>
                    <el-table-column prop="creationTime" label="创建时间" width="160"></el-table-column>
                    <el-table-column prop="lastModifiedTime" label="修改时间" width="160"></el-table-column>
                    <el-table-column prop="loginCount" label="登录次数"></el-table-column>
                    <el-table-column label="操作" align="center" min-width="70">
                        <template slot-scope="scope">
                            <el-tooltip content="编辑" placement="top">
                                <i class="fa fa-edit el-text-blue" @click="edit(scope.row.userId)"></i>
                            </el-tooltip>
                            <el-tooltip content="删除" placement="top">
                                <i class="fa fa-trash el-text-danger" @click="del(scope.row.userId)"></i>
                            </el-tooltip>
                        </template>
                    </el-table-column>
                </el-table>    
            </el-col>
        </el-row>
        <el-row>
            <el-col :span="24" class="table-bottom-margin" style="text-align:right">
                <el-pagination @size-change="pageSizeChange" @current-change="pageCurrentChange" :current-page="currentPage"
                    :page-sizes="[10]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="count">
                </el-pagination>
            </el-col>   
        </el-row>  
        <!--添加/编辑-->
        <el-dialog title="人员管理" :visible.sync="dialogFormVisible">
            <el-form :model="form" ref="form" :rules="rules" label-width="25%">
                
                <el-form-item label="用户类型：" prop="userLevel">
                    <el-select v-model.number="form.userLevel" @change="levelChange" placeholder="请选择用户类型" style="width:60%;">
                        <el-option :value="0" label="总控台"></el-option>
                        <el-option :value="1" label="场馆管理员"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item prop="gymId" v-if="form.userLevel">
                    <span slot="label" class="require-el">
                        场馆：
                    </span>
                    <el-select clearable v-model="form.gymId" placeholder="请选择场馆" style="width:60%;">
                        <el-option v-for="item in gymList" :value="item.gymId" :label="item.gymName" :key="item.gymId"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="用户名：" prop="userName">
                    <el-input v-model.trim="form.userName" placeholder="请输入用户名" style="width:60%;"></el-input>
                </el-form-item>
                <el-form-item label="密码：" prop="userPasswd">
                    <el-input type="password" v-model.trim="form.userPasswd" placeholder="请输入密码" style="width:60%;"></el-input>
                </el-form-item>
                <el-form-item label="确认密码：" prop="ConfirmPassWord">
                    <el-input type="password" v-model.trim="form.ConfirmPassWord" placeholder="请输入确认密码" style="width:60%;"></el-input>
                </el-form-item>
                <el-form-item label="是否有效：" prop="valid">
                    <el-radio-group v-model="form.valid">
                        <el-radio :label="true">是</el-radio>
                        <el-radio :label="false">否</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="save" size="medium">确 定</el-button>
                <el-button @click="dialogFormVisible = false" size="medium">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    export default {
        data(){
            var validatePass2 = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入确认密码'));
                } else if (value !== this.form.userPasswd) {
                    callback(new Error('两次输入密码不一致!'));
                } else {
                    callback();
                }
            };
            var validateGymId = (rule, value, callback)=>{
                if(this.form.userLevel && !value){
                    callback(new Error('请选择场馆'));
                }else{
                    callback();
                }
            };
            var checkUserName = (rule, value, callback)=>{
                if(this.timer){
                    clearTimeout(this.timer);
                }
                if(value){
                    this.timer = setTimeout(()=>{
                        remoteSearch(value);
                    },300);
                }

                var id = this.form.userId||'';
                var errorMess = '用户名重复';
                var that = this;
                function remoteSearch(keyword){
                    if(that.cancel){
                        that.cancel();
                    }
                    let CancelToken = axios.CancelToken;
                    axios.get(`user/checkUserName?userId=${id}&userName=${keyword}`,{
                        cancelToken: new CancelToken((c) => {
                            that.cancel = c;
                        })
                    }).then((res)=>{
                        callback();
                    }).catch((error)=>{
                        callback(new Error(errorMess));
                    });
                }
            }
            return{
                currentPage:1,
                pageSize:10,
                count:0,
                headerbg:'headerbg',//表格头部背景色
                tableData:[],
                rules:{
                    gymId:[
                        { validator: validateGymId, trigger: 'change' },
                    ],
                    userName:[
                        { required: true, message: '请输入用户名', trigger: 'blur' },
                        { min: 1, max:10, message: '长度在 1 到 10 个字符' },
                        { validator: checkUserName, trigger: ['change','blur'] }
                    ],
                    userPasswd:[
                        { required: true, message: '请输入密码', trigger: 'blur' },
                        { min: 8, max:16, message: '长度在 8 到 16 个字符' },
                    ],
                    ConfirmPassWord:[
                        { required: true, message: '请输入确认密码', trigger: 'blur' },
                        { validator: validatePass2, trigger: 'blur' },
                        { min: 8, max:16, message: '长度在 8 到 16 个字符' },
                    ]
                },
                searchForm:{
                    gymName:'',
                    userName:''
                },
                dialogFormVisible:false,
                form:{},
                gymList:[],
                loading:true,
                timer: null,
                cancel: null,
                preValInError: ''              
            }
        },
        components: {
        },
        created(){
            axios.get(`gym/listAll`,{
            })
            .then( (res)=> {
                this.gymList = res.data;
            })
        },
        mounted() {
            this.getList(10,this.currentPage);
        },
        methods:{
            levelChange(){//用户类型切换
                if(this.form.userLevel==0){
                    this.form.gymId = '0';
                }else{
                    this.form.gymId = '';
                }
            },
            search:function(){
                this.getList(10,this.currentPage);
            },
            getList:function(PageSize,PageIndex){
                this.loading=true;
                axios.get(`user/list?pageSize=${PageSize}&page=${PageIndex}&gymName=${this.searchForm.gymName}&userName=${this.searchForm.userName}`,{
                })
                .then( (res)=> {
                    this.count = res.total;
                    this.tableData = res.data.map(t=>{
                        t.creationTime = moment(t.creationTime).format("YYYY-MM-DD HH:mm:ss");
                        t.lastModifiedTime = moment(t.lastModifiedTime).format("YYYY-MM-DD HH:mm:ss");
                        return t;
                    });
                    this.loading=false;
                })
                .catch( (error)=> {
                    this.count = 0;
                    this.tableData = [];
                    this.$notify.error({title: '错误',message:error||'获取表格列表失败！'});
                });
            },
            del:function(id){
                this.$confirm('确定需要删除该人员?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    axios.delete(`user/remove?userId=${id}`,{},{
                    }).then((res)=>{
                        this.getList(10,this.currentPage);
                        this.$notify({title: '成功',message: '删除成功！',type: 'success'});
                    }).catch( (error)=> {
                        this.$notify.error({title: '错误',message:error||'删除失败！'});
                    });
                },()=>{})
            },
            add(){
                this.dialogFormVisible = true;
                this.form = {
                    userLevel:1,//场馆管理员
                    valid:true,
                    gymId:''
                };
                this.$nextTick(() => {
                    this.$refs.form.clearValidate();
                });
            },
            edit(id){
                this.dialogFormVisible = true;
                axios.get(`user/select?userId=${id}`,{},{
                }).then((res)=>{
                    var {lastModifiedTime,creationTime,loginCount,handler,...arr} = res.data;
                    arr.userPasswd = '';
                    this.form = arr;
                }).catch( (error)=> {
                });
            },
            save(){
                var errorInfo = this.validateFun();
                if(errorInfo){
                    this.$notify({title: '警告', message: errorInfo, type: 'warning',duration:1200});
                    return;
                }
                var {ConfirmPassWord, ...body} =this.form;
                axios[this.form.userId?'put':'post'](`user/${this.form.userId?'update':'add'}`,body,{}).then((res)=>{
                    this.getList(10, this.currentPage);
                    this.dialogFormVisible = false;
                }).catch((error)=>{
                    this.$notify.error({title: '错误',message:error || '保存失败！'});
                })
            },
            validateFun:function(){
                var errorInfo=[]; 
                this.$refs.form.validateField(['gymId','userName','userPasswd','ConfirmPassWord'],(re)=>{
                    if(re){
                        errorInfo.push(re);
                    }
                });
                return errorInfo.join('');
            },
            pageSizeChange:function(val){
                this.pageSize = val;
                this.getList(val, this.currentPage);
            },
            pageCurrentChange:function(val){
                this.currentPage = val;
                this.getList(this.pageSize,val);
            }
        }
    }
</script>
<style scoped>
    .require-el:before{
        content: '*';
        color: #F56C6C;
        margin-right: 4px;
    }
</style>